package Entity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PracticeManager {
    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final String PRACTICE_PERSON = "Xiaoming"; // 固定练习者姓名，无需传入

    // 正确的方法：仅接收1个参数（习题文件路径），返回练习文件路径
    public String startPracticeByExerciseFile(String exerciseFilePath) throws IOException {
        // 1. 校验习题文件合法性
        File exerciseFile = new File(exerciseFilePath);
        if (!exerciseFile.exists()) {
            throw new IllegalArgumentException("习题文件不存在：" + exerciseFilePath);
        }
        if (!exerciseFile.getName().startsWith("Exercise_") || !exerciseFile.getName().endsWith(".csv")) {
            throw new IllegalArgumentException("非法习题文件：" + exerciseFilePath);
        }

        // 2. 读取习题文件
        List<Exercise> exerciseList = CsvFileUtil.readExercises(exerciseFilePath);
        if (exerciseList.isEmpty()) {
            throw new IllegalArgumentException("习题文件为空：" + exerciseFilePath);
        }

        // 3. 生成练习文件路径（关联习题文件+练习者+日期）
        String exerciseFileName = exerciseFile.getName();
        String practiceDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String practiceFileName = exerciseFileName.replace(".csv", "_" + PRACTICE_PERSON + "_" + practiceDate + ".csv");
        String practiceFilePath = CsvFileUtil.BASE_DIR + practiceFileName;

        // 4. 初始化练习记录（未答题状态：userAnswer为null）
        List<PracticeRecord> practiceRecords = new ArrayList<>();
        String createTime = TIME_FORMAT.format(new Date());
        for (Exercise exercise : exerciseList) {
            practiceRecords.add(new PracticeRecord(
                    exercise.getExerciseId(),
                    null, // 未答题：Integer类型支持null
                    false,
                    createTime
            ));
        }

        // 5. 写入练习文件
        CsvFileUtil.writePracticeRecords(practiceRecords, practiceFilePath);
        System.out.println("练习文件创建成功：" + practiceFilePath);
        return practiceFilePath;
    }

    // 保存练习进度（无修改，已适配 Integer 类型）
    public void savePracticeProgress(String practiceFilePath, String exerciseId, Integer userAnswer) throws IOException {
        File practiceFile = new File(practiceFilePath);
        if (!practiceFile.exists()) {
            throw new IllegalArgumentException("练习文件不存在，无法保存进度：" + practiceFilePath);
        }

        List<PracticeRecord> practiceRecords = CsvFileUtil.readPracticeRecords(practiceFilePath);
        boolean isRecordFound = false;
        String currentTime = TIME_FORMAT.format(new Date());

        List<String> existingIds = new ArrayList<>();
        for (PracticeRecord record : practiceRecords) {
            String existingId = record.getExerciseId();
            existingIds.add(existingId);
            if (existingId.equals(exerciseId)) {
                record.setUserAnswer(userAnswer);
                record.setCompleted(userAnswer != null);
                record.setAnswerTime(currentTime);
                isRecordFound = true;
                break;
            }
        }

        if (!isRecordFound) {
            throw new RuntimeException(
                    "未找到习题ID：" + exerciseId + "，无法保存进度！\n" +
                            "练习文件中已存在的习题ID：" + existingIds
            );
        }

        CsvFileUtil.writePracticeRecords(practiceRecords, practiceFilePath);
        System.out.println("✅ 练习进度保存成功：");
        System.out.println(" - 习题ID：" + exerciseId);
        System.out.println(" - 用户答案：" + userAnswer);
    }

    // 恢复练习（无修改）
    public List<PracticeRecord> resumeInterruptedPractice(String practiceFilePath) throws IOException {
        File practiceFile = new File(practiceFilePath);
        if (!practiceFile.exists()) {
            throw new IllegalArgumentException("练习文件不存在，无法恢复练习：" + practiceFilePath);
        }

        List<PracticeRecord> allRecords = CsvFileUtil.readPracticeRecords(practiceFilePath);
        List<PracticeRecord> unfinishedRecords = new ArrayList<>();

        for (PracticeRecord record : allRecords) {
            if (!record.isCompleted() || record.getUserAnswer() == null) {
                unfinishedRecords.add(record);
            }
        }

        System.out.println("✅ 练习恢复成功：");
        System.out.println(" - 练习文件：" + practiceFilePath);
        System.out.println(" - 总习题数：" + allRecords.size());
        System.out.println(" - 未完成习题数：" + unfinishedRecords.size());
        return unfinishedRecords;
    }

    // 随机抽取习题文件（无修改）
    public String randomSelectOneExerciseFile(String exerciseType, String maxDate) {
        File dir = new File(CsvFileUtil.BASE_DIR);
        File[] exerciseFiles = dir.listFiles(file -> {
            String fileName = file.getName();
            return file.isFile()
                    && fileName.endsWith(".csv")
                    && fileName.startsWith("Exercise_" + exerciseType + "_")
                    && fileName.split("_")[2].compareTo(maxDate) <= 0;
        });

        if (exerciseFiles == null || exerciseFiles.length == 0) {
            throw new IllegalArgumentException("无符合条件的" + exerciseType + "类型习题文件（生成日期≤" + maxDate + "）");
        }

        int randomIndex = new java.util.Random().nextInt(exerciseFiles.length);
        String selectedFilePath = exerciseFiles[randomIndex].getAbsolutePath();
        System.out.println("✅ 随机抽取" + exerciseType + "类型习题文件：" + selectedFilePath);
        return selectedFilePath;
    }
}